package cre.redis.ch;

import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.*;

/**
 * @Author penglai
 * @Date 2017/3/6.
 */
public class Ch01 {

    public static final Long WEEK_SECONDS = 3600 * 24 * 7l;
    public static final Long VOTE_SCORE = 432l;
    public static final int DEFAULT_PAGE_SIZE = 20;

    public static final String TIME_KEY = "time:";
    public static final String SCORE_KEY = "score:";
    public static final String ARTICLE_PRE = "article:";
    public static final String VOTE_PRE = "vote:";
    public static final String USER_PRE = "user:";

    /**
     * 文章投票
     *
     * @param red
     * @param articleId
     * @param userId
     */
    public void articleVote(Jedis red, Integer articleId, Integer userId) {
        long now = System.currentTimeMillis();
        String articleKey = ARTICLE_PRE + articleId;

//        文章发布超出一周，不能投票
        if (red.zscore(TIME_KEY, articleKey) + WEEK_SECONDS < now) {
            return;
        }

//        一个用户只能投票一次
        String voteKey = VOTE_PRE + articleId;
        String userKey = USER_PRE + userId;
        if (red.sismember(voteKey, userKey)) {
            return;
        }

        red.sadd(voteKey, userKey);
        red.zincrby(SCORE_KEY, VOTE_SCORE, articleKey);
        red.hincrBy(articleKey, "vote", 1);
    }

    /**
     * 根据时间排序或者评分排序，获取文章
     *
     * @return
     */
    public List<Map<String, String>> getArticles(Jedis red, int pageNo, String orderKey) {
        if (StringUtils.isEmpty(orderKey)) {
            orderKey = SCORE_KEY;
        }
        int start = pageNo * DEFAULT_PAGE_SIZE;
        int end = start + DEFAULT_PAGE_SIZE - 1;

        List<Map<String, String>> ret = new ArrayList<>();
        Set<String> articles = red.zrevrange(orderKey, start, end);

        for (String article : articles) {
            Map<String, String> articleData = red.hgetAll(article);
            String aId = article.split(":")[1];
            articleData.put("id", aId);
            ret.add(articleData);
        }
        return ret;
    }

    /**
     * 发布新文章
     *
     * @return
     */
    public Integer postArticle(Jedis red, Integer userId, String title) {
        long now = System.currentTimeMillis();

//        创建文章hash
        Long aId = red.incr(ARTICLE_PRE);
        String aKey = ARTICLE_PRE + aId;
        Map<String, String> hash = new HashMap<>();

        hash.put("title", title);
        hash.put("author", userId + "");
        hash.put("vote", "1");

        red.hmset(aKey, hash);
//        设置各个数据结构
        red.sadd(VOTE_PRE + aId, USER_PRE + userId);
        red.expire(VOTE_PRE + aId, WEEK_SECONDS.intValue());

        red.zadd(TIME_KEY, now, aKey);
        red.zadd(SCORE_KEY, now, aKey);

        return aId.intValue();
    }

    public static void main(String[] args) {

    }

}
